from datetime import datetime
import glob, os, os.path
from xml.dom import minidom
from datetime import datetime

class ParsedFile():

    class Message():
        def __init__(self):
            self.type = None
            self.incoming = None
            self.time = None
            self.text = None

    def __init__(self):
        self.mintime = None
        self.messages = []

def parse(file):
    """
     Read and parse ICQ file. return ParsedFile object
    """
    infile = open(file, "r")
    try:
        xmldoc = minidom.parse(infile).documentElement
        #check version. Only supported is 0x00140034
        version = xmldoc.getElementsByTagName('version')
        if len(version) == 1:
            versionNumber = version[0].firstChild.nodeValue
            if versionNumber != '0x00140034':
                print '\t%s version is not supported' % versionNumber
                return None
        else:
            print '\tNot ICQ source file'
            return None
            
        parsedFile = ParsedFile()
        parsedFile.filename = file

        for event in  xmldoc.getElementsByTagName('event'):
            #print event.getElementsByTagName('text')[0].firstChild.nodeValue
            message = ParsedFile.Message()
            message.type = event.getElementsByTagName('type')[0].firstChild.nodeValue
            message.incoming = event.getElementsByTagName('incoming')[0].firstChild.nodeValue
            message.time = int(event.getElementsByTagName('time')[0].firstChild.nodeValue)
            message.text = event.getElementsByTagName('text')[0].firstChild.nodeValue

            parsedFile.messages.append(message)

            if parsedFile.mintime is None or parsedFile.mintime > message.time:
                parsedFile.mintime = message.time


        return parsedFile

    finally:
        if not infile.closed:
            infile.close()


def convert(indirectory, outfile = 'out.txt'):
    
    contact = os.path.basename(os.path.normpath(indirectory))
    parsedObjects = []

    for file in glob.glob(os.path.join(indirectory,'*.xml')):
            print 'parsing %s' % file
            parsedObjects.append(parse(file))

    #sort parsedObjects by mintime
    #print parsedObjects
    
    parsedObjects.sort(lambda x,y: x.mintime - y.mintime)
    #write messages to outfile
    out = open(outfile,'w')
    try:
        for parsedObject in parsedObjects:
            print 'Exporting %s messages from file %s' % \
                    (len(parsedObject.messages), parsedObject.filename)
            for message in parsedObject.messages:
                
                if message.incoming == 'Yes':
                    sender = contact 
                else:
                    sender = 'OUT' 

                formtime = datetime.fromtimestamp(message.time)

                out.write('%s %s: %s' % 
                        (formtime,sender,message.text.encode('utf-8')))
        
    finally:
        if not out.closed:
            out.close()
            

if __name__ == "__main__":
    #call for each directory, output is file named as icq num + txt
    #TODO where to get map of icqnum-> name?
    for f in os.listdir('.'):
        if os.path.isdir(f):
            convert(f, f + '.txt')
